<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <a-form :form="form">
        <a-row>
          <a-col :span="12">
            <a-form-item label="合同编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-decorator="['contractCode', validatorRules.contractCode]"
                placeholder="请输入合同编号"
              ></a-input>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-decorator="['name', validatorRules.name]"
                placeholder="请输入合同名称"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
  <a-form-item label="客户" v-if="businessId" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                :disabled="true"
                type="list"
                v-decorator="['customerId', validatorRules.customerId]"
                :dictCode="'CrmCustomer,customerName,id,customerId='+customerId"
                
              />
  </a-form-item>
          
          
            <a-form-item label="客户" v-else :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                :disabled="disableSubmit"
                type="list"
                v-decorator="['customerId',validatorRules.customerId]"
                :trigger-change="true"
                :dictCode="'CrmCustomer,customerName,id,ownerUserId='+ownerUserId"
                placeholder="请选择客户"
              />
            </a-form-item>
          </a-col>

          <!-- <a-col :span="12">
            <a-form-item label="商机id" v-if="businessId&&!model.id" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['businessId']" :disabled="true"></a-input>
            </a-form-item>
            <a-form-item label="商机" v-else :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                :disabled="disableSubmit"
                type="list"
                v-decorator="['businessId']"
                :trigger-change="true"
                dictCode="CrmBusiness,businessName,id"
                placeholder="请选择商机"
              />
            </a-form-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-item label="下单日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date
                :disabled="disableSubmit"
                placeholder="请选择下单日期"
                v-decorator="['orderDate']"
                :trigger-change="true"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date
                :disabled="disableSubmit"
                placeholder="请选择开始时间"
                v-decorator="['startTime']"
                :trigger-change="true"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date
                :disabled="disableSubmit"
                placeholder="请选择结束时间"
                v-decorator="['endTime']"
                :trigger-change="true"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="合同金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="disableSubmit" v-decorator="['money', validatorRules.money]" placeholder="请输入合同金额"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="整单折扣" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="disableSubmit" v-decorator="['discountRate']" placeholder="请输入整单折扣"></a-input>
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="合同类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="disableSubmit" v-decorator="['types']" placeholder="请输入合同类型"></a-input>
            </a-form-item>
            </a-col> -->
          <!-- <a-col :span="12">
            <a-form-item label="付款方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag :disabled="disableSubmit" type="list" v-decorator="['paymentType']" :trigger-change="true" dictCode="" placeholder="请选择付款方式"/>
            </a-form-item>
            </a-col> -->
          <!-- <a-col :span="12">
            <a-form-item label="客户签约人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag :disabled="disableSubmit" type="list" v-decorator="['contactsId']" :trigger-change="true" dictCode="" placeholder="请选择客户签约人"/>
            </a-form-item>
            </a-col> -->
          <a-col :span="12">
            <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="disableSubmit" v-decorator="['remark']" placeholder="请输入备注"></a-input>
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="公司签约人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag :disabled="disableSubmit" type="list" v-decorator="['companyUserId']" :trigger-change="true" dictCode="" placeholder="请选择公司签约人"/>
            </a-form-item>
            </a-col> -->
          <!-- <a-col :span="12">
            <a-form-item label="最后跟进时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="disableSubmit" v-decorator="['lastTime']" placeholder="请输入最后跟进时间"></a-input>
            </a-form-item>
          </a-col> -->
        </a-row>
      </a-form>

      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane tab="合同明细表" :key="refKeys[0]" :forceRender="true">
          <j-editable-table
            :disabled="disableSubmit"
            :ref="refKeys[0]"
            :tableName="refKeys[0]"
            :loading="crmContractItemTable.loading"
            :columns="crmContractItemTable.columns"
            :dataSource="crmContractItemTable.dataSource"
            :maxHeight="300"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true"
            @valueChange="itemChange"
          />
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </j-modal>
</template>

<script>
import pick from 'lodash.pick'
import { FormTypes, getRefPromise } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { validateDuplicateValue } from '@/utils/util'
import { mapGetters } from 'vuex'
import JDate from '@/components/jeecg/JDate'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
export default {
  name: 'CrmContractModal',
  mixins: [JEditableTableMixin],
  components: {
    JDate,
    JDictSelectTag,
  },
  props: {
    customerId: {
      type: String,
      default: '',
    },
    businessId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      ownerUserId: this.userInfo().userLoginId,
      disableSubmit: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        contractCode: {
          rules: [{ required: true, message: '请输入合同编号!' }],
        },
        name: {
          rules: [{ required: true, message: '请输入合同名称!' }],
        },
        customerId: {
          rules: [{ required: true, message: '请选择客户!' }],
        },
        money: {
          rules: [
            { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确的金额!' },
          ],
          
        },
      },
      refKeys: ['crmContractItem'],
      tableKeys: ['crmContractItem'],
      activeKey: 'crmContractItem',
      // 合同明细表
      crmContractItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '分类',
            key: 'categoryName',
            type: FormTypes.select,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            dictCode: 'DataDictionary,description,dictionaryId,dictionaryTypeId=PRODUCT_TYPE',
            validateRules: [{ required: true, message: '请选择分类!' }]
          },
 {
            title: '产品名称',
            key: 'name',
            type: FormTypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '请输入名称!' }]
          },
{
            title: '产品单位',
            key: 'unit',
            type: FormTypes.select,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            dictCode: 'DataDictionary,description,dictionaryId,dictionaryTypeId=PRODUCT_UNIT',
            validateRules: [{ required: true, message: '请选择产品单位!' }]
          },
          {
            title: '标准价格',
            key: 'price',
            type: FormTypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
  
 
          {
            title: '售价',
            key: 'salesPrice',
            type: FormTypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
{
            title: '数量',
            key: 'num',
            type: FormTypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '折扣比例(%)',
            key: 'discount',
            type: FormTypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '100',
	    validateRules: [
                {pattern: /^-?\d+$/, message: '请输入整数!'},
                {pattern: /\d{0,2}/, message: '请输入100以内的数字!'},
            ]
          },
         
        
          {
            title: '小计',
            key: 'subtotal',
            type: FormTypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
         
        ],
      },
      url: {
        add: '/online/special/api/createCrmContract',
        edit: '/online/special/api/updateCrmContract',
        crmContractItem: {
          list: '/online/api/pagingContractItemList',
          deleteBatch: '/online/api/deleteCrmContractItemByCrmContractBatch',
        },
      },
    }
  },
  methods: {
    ...mapGetters(['userInfo']),
    async itemChange(event) {
      const {type, row, column, value, target} = event
      if (column.key === 'discount'||column.key === 'num'||column.key === 'salesPrice'){
          let discount = row.discount
          if(!discount) discount = 0;
          let num = row.num
          if(!num) num = 0;
          let salesPrice = row.salesPrice
          if(!salesPrice) salesPrice = 0;
          let subtotal = parseFloat(discount)*parseFloat(num)*parseFloat(salesPrice)/100
          target.setValues([
          {
            rowKey: row.id,
            values: { subtotal:subtotal},
          },
        ])
      }
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      if (this.customerId) {
        this.model.customerId = this.customerId
      }
      if (this.businessId) {
        this.model.businessId = this.businessId
      }
      let fieldval = pick(
        this.model,
        'contractCode',
        'name',
        'customerId',
        'businessId',
        'checkStatus',
        'examineRecordId',
        'orderDate',
        'createUserId',
        'ownerUserId',
        'createTime',
        'updateTime',
        'num',
        'startTime',
        'endTime',
        'money',
        'discountRate',
        'totalPrice',
        'types',
        'paymentType',
        'batchId',
        'roUserId',
        'rwUserId',
        'contactsId',
        'remark',
        'companyUserId',
        'lastTime',
        'list'
      )
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { contractId: this.model.id }
        this.requestSubTableData(this.url.crmContractItem.list, params, this.crmContractItemTable)
      }
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        product: allValues.tablesValue[0].values,
      }
    },
    validateError(msg) {
      if (msg) {
        this.isHandleOk = false
      }
      this.$message.error(msg)
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          'contractCode',
          'name',
          'customerId',
          'businessId',
          'checkStatus',
          'examineRecordId',
          'orderDate',
          'createUserId',
          'ownerUserId',
          'createTime',
          'updateTime',
          'num',
          'startTime',
          'endTime',
          'money',
          'discountRate',
          'totalPrice',
          'types',
          'paymentType',
          'batchId',
          'roUserId',
          'rwUserId',
          'contactsId',
          'remark',
          'companyUserId',
          'lastTime',
          'list'
        )
      )
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .ant-modal-mask {
  z-index: 98;
  background-color: rgb(245, 246, 249);
}
/deep/ .ant-modal-wrap {
  z-index: 99;
}
/deep/ .ant-modal-title {
  color: #333;
  font-weight: 700;
  font-size: 17px;
}
</style>